<template>
  <div class="json-editor-container">
    <div v-if="editor" class="editor-controls">
      <button @click="insertPlaceholder('quickDateType')">插入 quickDateType</button>
      <button @click="insertPlaceholder('startTime')">插入 startTime</button>
      <button @click="insertPlaceholder('endTime')">插入 endTime</button>
      <button @click="getJsonData">获取 JSON 数据</button>
    </div>

    <editor-content :editor="editor" class="json-editor" />

    <div v-if="outputJson" class="json-output">
      <h3>生成的 JSON:</h3>
      <pre>{{ outputJson }}</pre>
    </div>
  </div>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import JsonPlaceholderExtension from './JsonPlaceholderExtension'

export default {
  components: {
    EditorContent,
  },

  data() {
    return {
      editor: null,
      outputJson: null,
      initialJson: {
        // dateType: 'day',
        // quickDateType: '{x}quickDateType',
        // startTime: '{x}startTime',
        // endTime: '{x}endTime',
      },
    }
  },

  mounted() {
    this.editor = new Editor({
      extensions: [
        StarterKit,
        Placeholder.configure({
          placeholder: '编辑你的 JSON 数据...',
        }),
        JsonPlaceholderExtension,
      ],
      content: this.formatInitialContent(),
      editorProps: {
        attributes: {
          class: 'json-editor',
        },
      },
    })
  },

  methods: {
    formatInitialContent() {
      const jsonString = JSON.stringify(this.initialJson, null, 2)
      const lines = jsonString.split('\n')
      let htmlContent = ''

      lines.forEach((line) => {
        const placeholderMatch = line.match(/\{x\}(\w+)/)
        if (placeholderMatch) {
          const key = placeholderMatch[1]
          htmlContent += `<span>${key}</span>:<span data-key="${key}" style="color: #888;">${key}</span>`
        } else {
          htmlContent += line
        }
        htmlContent += '\n'
      })

      return htmlContent
    },

    insertPlaceholder(key) {
      this.editor.chain().focus().insertJsonPlaceholder(key).run()
    },

    getJsonData() {
      const editorContent = this.editor.getHTML()
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = editorContent

      // 替换占位符为原始格式
      const placeholders = tempDiv.querySelectorAll('[data-key]')
      placeholders.forEach((el) => {
        const key = el.getAttribute('data-key')
        el.outerHTML = `{x}${key}`
      })

      const plainText = tempDiv.textContent
      console.log('plainText', plainText)

      try {
        this.outputJson = JSON.parse(plainText)
      } catch (error) {
        console.error('JSON 解析错误:', error)
        this.outputJson = { error: '无效的 JSON 格式' }
      }
    },
  },

  beforeUnmount() {
    this.editor?.destroy()
  },
}
</script>

<style>
.json-editor-container {
  max-width: 800px;
  margin: 0 auto;
}

.editor-controls {
  margin-bottom: 1rem;
}

.editor-controls button {
  margin-right: 0.5rem;
  padding: 0.25rem 0.5rem;
}

.json-editor {
  font-family: monospace;
  white-space: pre;
  border: 1px solid #ccc;
  padding: 10px;
  min-height: 200px;
  margin-bottom: 1rem;
}

.json-output {
  background: #f5f5f5;
  padding: 1rem;
  border-radius: 4px;
}

.json-output pre {
  margin: 0;
  white-space: pre-wrap;
}
</style>
